package cn.topevery.garden.wapi.service;

import cn.topevery.garden.wapi.client.IoTSocketClient;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;

/**
 * @author ：peng.tian
 * @date ：Created in 2021/9/8 10:41
 * @description：socket数据接入入口
 */
@SpringBootApplication
public class IoTSocketService implements CommandLineRunner {

    private int port=7001;

    @Override
    public void run(String... args) throws Exception {
        ServerSocket serverSocket=null;
        try {
            serverSocket=new ServerSocket(port);  //端口号

            System.out.println("时间:" + LocalDateTime.now() + ",端口:"+port+",socket服务端开启!");

            //通过死循环开启长连接，开启线程去处理消息
            while(true){
                Socket socket=serverSocket.accept();
                new Thread(new IoTSocketClient(socket)).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (serverSocket!=null) {
                    serverSocket.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

}
